package main

import (
	"cronjob_work/common/commfunc"
	"cronjob_work/common/jobs"
	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"os"
	"os/signal"
	"syscall"

	_ "cronjob_work/internal/logic"
	_ "cronjob_work/internal/packed"

	"time"
)

func main() {
	ctx := gctx.New()
	err, key, pool, etcdclient := commfunc.Init(ctx)
	if err != nil {
		g.Log().Error(ctx, "初始化失败"+err.Error())
		return
	}

	jobs.Init(ctx, pool)                                          //启动cron的jobs
	commfunc.InitEtcd(ctx, key, etcdclient)                       //初始化etc并且初始化jobs，将jobs和cron绑定
	go etcdclient.WatchWithDeal(ctx, key, commfunc.WatchCallback) //添加etcd的监听
	state := 1
	sic := make(chan os.Signal)
	signal.Notify(sic, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)

EXIT:
	for {

		sig := <-sic
		g.Log().Infof(ctx, "Receive signal[%s]", sig.String())
		switch sig {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			state = 0
			break EXIT
		case syscall.SIGHUP:
		default:
			break EXIT
		}
	}

	etcdclient.Stop()
	jobs.MainCron.Stop()
	g.Log().Info(ctx, "stop cron deal .....")
	time.Sleep(time.Second * 10)
	g.Log().Info(ctx, "system is exit.....")
	os.Exit(state)

}
